package com.jnyoubo.autolxr;

import android.Manifest;
import android.app.AlertDialog;
import android.content.*;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.*;
import androidx.appcompat.app.AppCompatActivity;
import com.blankj.utilcode.util.CacheDiskUtils;
import com.blankj.utilcode.util.DeviceUtils;
import com.qw.soul.permission.SoulPermission;
import com.qw.soul.permission.bean.Permission;
import com.qw.soul.permission.bean.Permissions;
import com.qw.soul.permission.callbcak.CheckRequestPermissionsListener;

import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 *
 * @author macy
 */
public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    /**
     * 核心线程数
     */
    private final int CORE_POOL_SIZE = 5;
    /**
     * 最大线程数
     */
    private final int MAX_POOL_SIZE = 10;
    /**
     * 空闲线程超时时间
     */
    private final long KEEP_ALIVE_TIME = 10;
    private ThreadPoolExecutor executorPool;

    EditText gjh;
    EditText qzh;
    EditText sch;
    EditText buqihao;
    EditText sl;
    EditText text;
    TextView jiqima;
    TextView wx;

    Button kscj;
    Button qkh;
    Button shouquan;

    LinearLayout sqview;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        gjh=findViewById(R.id.gjh);
        qzh=findViewById(R.id.qzh);
        sch=findViewById(R.id.sch);
        buqihao=findViewById(R.id.buqihao);
        sl=findViewById(R.id.sl);
        text=findViewById(R.id.text);
        kscj=findViewById(R.id.kscj);
        qkh=findViewById(R.id.qkh);
        jiqima=findViewById(R.id.jiqima);
        shouquan=findViewById(R.id.shouquan);
        wx=findViewById(R.id.wx);
        sqview=findViewById(R.id.sqview);

        kscj.setOnClickListener(this);
        qkh.setOnClickListener(this);
        wx.setOnClickListener(this);
        shouquan.setOnClickListener(this);


        // 创建线程池
        // 创建一个核心线程数为4、最大线程数为5的线程池
        executorPool = new ThreadPoolExecutor(CORE_POOL_SIZE, MAX_POOL_SIZE, KEEP_ALIVE_TIME,
                TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(),
                Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy());



        if(null==CacheDiskUtils.getInstance().getString("jiqima",null)){
            CacheDiskUtils.getInstance().put("jiqima",DeviceUtils.getAndroidID().trim().toUpperCase());
        }

        jiqima.setText(""+CacheDiskUtils.getInstance().getString("jiqima"));
        jiqima.setOnClickListener(this);



        initPermissions();
    }

    @Override
    protected void onResume() {
        super.onResume();
        initShowQuan();//是否显示授权
    }

    private void initShowQuan(){
        if(CacheDiskUtils.getInstance().getString("authorization",null)==null){
            sqview.setVisibility(View.VISIBLE);
        }else{
            sqview.setVisibility(View.GONE);
        }
    }


    private void initView(){

    }


    @Override
    public void onClick(View v) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        switch (v.getId()){
            case R.id.shouquan:
                startActivity(new Intent(this,SqActivity.class));
                break;
            case R.id.wx:
                setClipboard("shaoyecf");
                break;
            case R.id.kscj:
                if(CacheDiskUtils.getInstance().getString("authorization",null)==null){
                    builder.setTitle("提示");
                    builder.setMessage("当前设备未授权只能连续创建5个联系人");
                    builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            sl.setText(""+5);
                            cjlxr();
                        }
                    });
                    builder.setNegativeButton("取消",null);
                    builder.show();
                }else{
                    cjlxr();
                }
                break;
            case R.id.qkh:
                qklxr();
                break;
            case R.id.jiqima:
                setClipboard(jiqima.getText().toString());
                break;
        }
    }




    public void setClipboard(String text){
        //获取剪贴板管理器：
        ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        // 创建普通字符型ClipData
        ClipData mClipData = ClipData.newPlainText("Label", text);
        // 将ClipData内容放到系统剪贴板里。
        cm.setPrimaryClip(mClipData);

        Toast.makeText(this, "已复制", Toast.LENGTH_SHORT).show();
    }



    private void qklxr(){
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("提示");
        builder.setMessage("确定要删除通讯录所有联系人吗?");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                try {
                    Util.deleAll(MainActivity.this);
                } catch (Exception e) {
                    //Util.deleAll(MainActivity.this);
                }
            }
        });
        builder.setNegativeButton("取消",null);
        builder.show();
    }

    private void cjlxr(){
        AlertDialog.Builder builder = new AlertDialog.Builder(this);

        builder.setTitle("提示");
        builder.setMessage("确定要根据规则创建联系人吗？");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                try {
                    kscj();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        builder.setNegativeButton("取消",null);
        builder.show();

    }

    public class WorkerThread implements Runnable {
        private String name;
        private String phoneNumber;

        public WorkerThread(String name, String phoneNumber) {
            this.name = name;
            this.phoneNumber = phoneNumber;
        }

        @Override
        public synchronized void run() {
            try {
                Util.addContact(MainActivity.this,name,phoneNumber);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    /**
     * 开始创建
     */
    private void kscj(){
        try{
            text.setText("");

            String p=gjh.getText().toString().trim()+qzh.getText().toString().trim();
            int length=Integer.valueOf(buqihao.getText().toString().trim());

            int shu=Integer.valueOf(sch.getText().toString().trim());

            int max=Integer.valueOf(sl.getText().toString());
            String temp="";
            String buwei="";
            String name="";
            for (int i=0;i<max;i++){

                temp=p+""+(shu);
                if((temp.length()-gjh.getText().length())>length){
                    break;
                }
                buwei="";


                int bwmax=(length-(temp.length()-gjh.getText().length()));


                for (int t=0;t<bwmax;t++){
                    buwei+="0";
                }

                temp=p+buwei+(shu);
                name=qzh.getText().toString().trim()+buwei+(shu);
                append(temp);

                executorPool.execute(new WorkerThread(name,temp)); //开启线程任务

                shu++;
            }
        }catch (Exception e){
            Toast.makeText(this, "配置有误", Toast.LENGTH_SHORT).show();
        }
    }


    private void initPermissions(){
        SoulPermission.getInstance().checkAndRequestPermissions(
                Permissions.build(
                        Manifest.permission.READ_PHONE_STATE,
                        Manifest.permission.INTERNET,
                        Manifest.permission.READ_CONTACTS,
                        Manifest.permission.WRITE_CONTACTS
                        ), new CheckRequestPermissionsListener() {
                    @Override
                    public void onAllPermissionOk(Permission[] allPermissions) {
                        initView();
                    }

                    @Override
                    public void onPermissionDenied(Permission[] refusedPermissions) {
                        initPermissions();
                    }
                });
    }



    private void append(String str){
        text.setText(text.getText().toString()+"\n"+str);
    }




    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finish();
        }
        return super.onKeyDown(keyCode, event);
    }
}
